<template>
  <basic-container>
    <avue-crud
      :option="option"
      :table-loading="loading"
      v-model="form"
      :data="data"
      :page.sync="page"
      :permission="permissionList"
      :before-open="beforeOpen"
      :before-close="beforeClose"
      ref="crud"
      @row-update="rowUpdate"
      @row-save="rowSave"
      @row-del="rowDel"
      @search-change="searchChange"
      @search-reset="searchReset"
      @current-change="currentChange"
      @size-change="sizeChange"
      @refresh-change="refreshChange"
      @tree-load="treeLoad"
      @on-load="onLoad"
    >
      、
      <template slot-scope="scope" slot="menu">
        <el-button type="text" icon="el-icon-circle-plus-outline" size="small" :disabled="scope.row.parentId" @click.stop="handleAdd(scope.row)">新增子项 </el-button>
      </template>
    </avue-crud>
    <common-modal-template ref="commonModalTemplate" :option="tableOption" @getSelectedRows="getSelectedRows"></common-modal-template>
  </basic-container>
</template>
<script>
import { mapGetters } from 'vuex';
import userTableConfig from '@/components/user-table-config/index.vue';
import userConfig from '@/mixins/userConfig';
import CommonModalTemplate from '@/components/common-modal-template/common-modal-template.vue';
import { getFatherColumn, sonColumn } from '@/views/system/pageSource';
import { getPageList, getPageModel, remove, submit, getChild } from '@/api/system/pageSource';

export default {
  name: 'pageSource', // 会渲染成传入的componentName
  components: {
    userTableConfig,
    CommonModalTemplate
  },
  mixins: [userConfig()],
  data() {
    return {
      form: {},
      query: {},
      loading: true,
      page: {
        pageSize: 20,
        currentPage: 1,
        total: 0
      },
      modalName: '',
      tableOption: {},
      data: [],
      option: {
        calcHeight: 30,
        height: 'calc(100vh - 450px)',
        tip: false,
        lazy: true,
        rowKey: 'id',
        rowParentKey: 'parentId',
        searchShow: true,
        searchMenuSpan: 4,
        border: true,
        index: true,
        viewBtn: true,
        viewBtnText: '详情',
        editBtn: true,
        delBtn: true,
        addBtn: true,
        indexLabel: '序号',
        columnBtn: false,
        menuWidth: 300,
        column: getFatherColumn(this)
      }
    };
  },
  mounted() {
    this.$nextTick(() => {
      this.$structuralSplit();
    });
  },
  computed: {
    ...mapGetters(['permission']),
    permissionList() {
      return {
        addBtn: this.vaildData(this.permission, false),
        viewBtn: this.vaildData(this.permission, false),
        delBtn: this.vaildData(this.permission, false),
        editBtn: this.vaildData(this.permission, false)
      };
    }
  },
  methods: {
    async rowSave(row, done, loading) {
      if (this.addType === 'addSon') {
        row.parentId = this.parentId;
      }
      try {
        await this.submitInfo(row);
        this.$message.success('保存成功');
        this.addType = '';
        this.parentId = '';
        done();
        this.onLoad(this.page);
      } catch (e) {
        loading();
      }
    },
    handleAdd(row) {
      this.parentId = row.id;
      this.addType = 'addSon';
      this.$set(this.option, 'addTitle', '新增子项');
      this.$refs.crud.rowAdd();
    },
    async rowUpdate(row, index, done, loading) {
      try {
        await this.submitInfo(row);
        this.$message.success('保存成功');
        this.addType = '';
        done(row);
        this.onLoad(this.page);
      } catch (e) {
        loading();
      }
    },
    async submitInfo(row) {
      const res = await submit(row);
    },
    rowDel(row, index, done) {
      if (row.hasChild) {
        this.$message.warning('请将该页面下的功能区子项删除后，再删除该主页信息');
        return;
      } else if (row.type === 'PAGE') {
        this.$confirm(`是否确认将${row.name}页面信息删除`, {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(async () => {
          try {
            await remove({ ids: row.id });
            this.$message({
              type: 'success',
              message: '操作成功!'
            });
            this.onLoad(this.page);
          } catch (e) {
            console.warn(e);
          }
        });
      } else {
        const pageInfo = this.data.find((i) => row.parentId === i.id);
        this.$confirm(`是否确认将${pageInfo.name}页面功能区信息删除`, {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(async () => {
          try {
            await remove({ ids: row.id });
            this.$message({
              type: 'success',
              message: '操作成功!'
            });
            // 数据回调进行刷新
            done(row);
          } catch (e) {
            console.warn(e);
          }
        });
      }
    },
    beforeOpen(done, type) {
      if (type === 'add') {
        if (this.addType === 'addSon') {
          this.$set(this.option, 'column', sonColumn);
        } else {
          this.$set(this.option, 'addTitle', '新增');
          this.form.type = 'PAGE';
          this.$set(this.option, 'column', getFatherColumn(this));
        }
      } else {
        if (this.form.parentId) {
          this.$set(this.option, 'column', sonColumn);
        } else {
          this.$set(this.option, 'column', getFatherColumn(this));
        }
      }
      this.$refs.crud.refreshTable();
      done();
    },
    beforeClose(done, type) {
      this.parentId = '';
      this.addType = '';
      this.$set(this.option, 'column', getFatherColumn(this));
      this.$refs.crud.refreshTable();
      done();
    },
    searchReset() {
      this.query = {};
      this.onLoad(this.page);
    },
    searchChange(params, done) {
      this.query = params;
      this.page.currentPage = 1;
      this.onLoad(this.page, params);
      done();
    },
    async treeLoad(tree, treeNode, resolve) {
      const parentId = tree.id;
      const res = await getChild({ parentId });
      const data = res.data.data;
      resolve(data);
    },
    currentChange(currentPage) {
      this.page.currentPage = currentPage;
    },
    sizeChange(pageSize) {
      this.page.pageSize = pageSize;
    },
    refreshChange() {
      this.onLoad(this.page, this.query);
    },
    async onLoad(page, params = {}) {
      this.loading = true;
      const res = await getPageList(Object.assign(params, this.query, { current: page.currentPage, size: page.pageSize }));
      const data = res.data.data;
      this.page.total = data.total;
      this.data = data.records;
      try {
      } catch (e) {
        console.warn(e);
      } finally {
        this.loading = false;
      }
    },
    async getSelectedRows(rowData) {
      this.form.code = rowData.path;
      this.form.name = rowData.name;
      const res = await getPageModel(rowData.id);
      const data = res.data.data;
      this.form.rootMenuCode = data.code;
      this.form.rootMenuName = data.name;
      console.log(res.data);
    },
    openMenuModel() {
      this.$refs.commonModalTemplate.showModal();
      this.tableOption = {
        modalTitle: '选择页面（双击进行选择）',
        url: '/api/blade-system/menu/page?category=1',
        isPage: true,
        rowSelectionType: 'single',
        columnDefs: [
          {
            label: '菜单名称',
            prop: 'name',
            search: true
          },
          {
            label: '菜单编号',
            prop: 'code',
            search: true
          }
        ]
      };
    }
  }
};
</script>
<style lang="scss" scoped></style>
